<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use think\Db;

/**
 * 用户身份管理
 *
 */
class Identity extends Backend
{
    
    /**
     * 不再使用模型对象
     */
    protected $model = null;
    
    protected $searchFields = 'id,name';
    protected $modelValidate = true;
    protected $modelSceneValidate = true;
    protected $noNeedRight = [];

    public function _initialize()
    {
        parent::_initialize();
        // 不再需要初始化模型对象
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = Db::name('user_identity')
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = Db::name('user_identity')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            // 处理status_text字段和百分比字段
            foreach ($list as &$item) {
                $item['status_text'] = $item['status'] == 1 ? __('Normal') : __('Hidden');
                
                // 处理小数字段转换为百分比显示
                if (isset($item['direct_reward'])) {
                    $item['direct_reward'] = $item['direct_reward'] * 100;
                }
                if (isset($item['indirect_reward'])) {
                    $item['indirect_reward'] = $item['indirect_reward'] * 100;
                }
                if (isset($item['indirect_reward_count'])) {
                    $item['indirect_reward_count'] = $item['indirect_reward_count'] * 100;
                }
            }
            unset($item);
            
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = "Identity";
                        $validate = is_bool($this->modelValidate) ? ("\\app\\admin\\validate\\user\\" . $name) : $this->modelValidate;
                        $this->validateFailException(true)->validate($params, $validate);
                    }
                    
                    // 处理百分比字段转换为小数 - 移到验证之后
                    if (isset($params['direct_reward'])) {
                        $params['direct_reward'] = $params['direct_reward'] / 100;
                    }
                    if (isset($params['indirect_reward'])) {
                        $params['indirect_reward'] = $params['indirect_reward'] / 100;
                    }
                    if (isset($params['indirect_reward_count'])) {
                        $params['indirect_reward_count'] = $params['indirect_reward_count'] / 100;
                    }
                    
                    // 添加创建时间和更新时间
                    $params['createtime'] = $params['updatetime'] = time();
                    $result = Db::name('user_identity')->insert($params);
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }
    
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = Db::name('user_identity')->where('id', $ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                $result = false;
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = "Identity";
                        $validate = is_bool($this->modelValidate) ? ("\\app\\admin\\validate\\user\\" . $name) : $this->modelValidate;
                        $this->validateFailException(true)->validate($params, $validate);
                    }
                    
                    // 处理百分比字段转换为小数 - 移到验证之后
                    if (isset($params['direct_reward'])) {
                        $params['direct_reward'] = $params['direct_reward'] / 100;
                    }
                    if (isset($params['indirect_reward'])) {
                        $params['indirect_reward'] = $params['indirect_reward'] / 100;
                    }
                    if (isset($params['indirect_reward_count'])) {
                        $params['indirect_reward_count'] = $params['indirect_reward_count'] / 100;
                    }
                    
                    // 更新时间
                    $params['updatetime'] = time();
                    $result = Db::name('user_identity')->where('id', $ids)->update($params);
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        // 处理小数字段转换为百分比显示
        if (isset($row['direct_reward'])) {
            $row['direct_reward'] = $row['direct_reward'] * 100;
        }
        if (isset($row['indirect_reward'])) {
            $row['indirect_reward'] = $row['indirect_reward'] * 100;
        }
        if (isset($row['indirect_reward_count'])) {
            $row['indirect_reward_count'] = $row['indirect_reward_count'] * 100;
        }
        
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    
    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = 'id';
            $adminIds = $this->getDataLimitAdminIds();
            $where = [];
            if (is_array($adminIds)) {
                $where[$this->dataLimitField] = ['in', $adminIds];
            }
            $where[$pk] = ['in', $ids];
            
            $count = Db::name('user_identity')->where($where)->delete();
            
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
    
    /**
     * 批量更新
     */
    public function multi($ids = "")
    {
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            if ($this->request->has('params')) {
                parse_str($this->request->post("params"), $values);
                $values = array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
                if ($values || $this->auth->isSuperAdmin()) {
                    $adminIds = $this->getDataLimitAdminIds();
                    $where = [];
                    if (is_array($adminIds)) {
                        $where[$this->dataLimitField] = ['in', $adminIds];
                    }
                    $where['id'] = ['in', $ids];
                    
                    // 更新时间
                    $values['updatetime'] = time();
                    $count = Db::name('user_identity')->where($where)->update($values);
                    
                    if ($count) {
                        $this->success();
                    } else {
                        $this->error(__('No rows were updated'));
                    }
                } else {
                    $this->error(__('You have no permission'));
                }
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

